<template>
  <div>
    <el-menu
      :default-active="defaultActiveIndex()"
      class="el-menu-vertical-demo"
      :collapse="collapsed"
      :unique-opened="true"
      :router="true"
      @open="handleOpen"
      @close="handleClose"
    >
      <template
        v-for="route in menuRoutes"
        :key="route.path"
      >
        <!-- 有子路由的菜单项 -->
        <el-sub-menu
          v-if="route.children && route.children.length > 0"
          :index="route.path"
        >
          <template #title>
            <el-icon>
              <component :is="route.meta?.icon" />
            </el-icon>
            <span>{{ route.meta?.title }}</span>
          </template>
          <el-menu-item
            v-for="child in route.children"
            :key="child.path"
            :index="child.path"
            :route="{ path: child.path }"
          >
            <el-icon>
              <component :is="child.meta?.icon" />
            </el-icon>
            <span>{{ child.meta?.title }}</span>
          </el-menu-item>
        </el-sub-menu>

        <!-- 没有子路由的菜单项 -->
        <el-menu-item
          v-else
          :index="route.path"
          :route="{ path: route.path }"
          :disabled="route.meta?.disabled"
        >
          <el-icon>
            <component :is="route.meta?.icon" />
          </el-icon>
          <span>{{ route.meta?.title }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>
<script lang="ts" setup>
import { useRouter, useRoute } from 'vue-router'
import { onMounted, ref } from 'vue'

const router = useRouter()
const route = useRoute()
defineProps({
  collapsed: {
    type: Boolean,
    default: false,
  },
})

// 获取需要显示在菜单中的路由
const menuRoutes = ref()

const constructMenuRoutes = () => {
  const rootRoute = router.getRoutes().find(route => route.path === '/')
  return rootRoute?.children
    ?.filter(route => !route.meta?.hideInMenu) || []
}

const defaultActiveIndex = () => {
  return route.path
}

const handleOpen = (key: string, keyPath: string[]) => {
  // console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  // console.log(key, keyPath)
}

onMounted(() => {
  menuRoutes.value = constructMenuRoutes()
  // console.log('menuRoutes', menuRoutes.value, router.options.routes)
})

</script>
<style scoped>
.el-menu {
  border: 0px;
}

.el-menu-item.is-active {
  background-color: #f5f5f5 !important;
}

/* .el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
} */
</style>